package com.zb.security.tag;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.common.base.Strings;
import com.zb.common.po.enums.MenuType;
import com.zb.common.po.model.Menu;
import com.zb.common.po.model.SessionUser;
import com.zb.common.utils.Constants;
import com.zb.service.MenuService;

public class MenuTag extends TagSupport {

    private static final Logger logger = Logger.getLogger(MenuTag.class);

    private static final long serialVersionUID = -1707052946995139413L;

    private static final int MARGIN_UNIT = 15;

    @Override
    public int doStartTag() throws JspException {
        HttpServletRequest request = (HttpServletRequest) pageContext
                .getRequest();
        JspWriter out = this.pageContext.getOut();
        StringBuilder menuBuilder = new StringBuilder();

        String requestURI = request.getRequestURI();
        logger.info("[菜单]获取选中的菜单URI： " + requestURI);

        if (Strings.isNullOrEmpty(requestURI)) {
            return SKIP_BODY;
        }
        SessionUser sessionUser = (SessionUser) request.getSession()
                .getAttribute(Constants.SESSION_KEY);
        boolean flag = false;

        List<Menu> menus = sessionUser.getMenuList();
        if (menus != null && !menus.isEmpty()) {
            flag = true;
        }

        WebApplicationContext webApplicationContext = WebApplicationContextUtils
                .getWebApplicationContext(request.getSession()
                        .getServletContext());
        MenuService menuService = (MenuService) webApplicationContext
                .getBean("menuService");
        // 查询当前请求的url的父菜单，目的是在进入子页面的时候，左侧菜单也能选中
        Menu curUrlPMenu = menuService.findPmenuByUrl(requestURI);

        menuBuilder = getChildMenue(menus, 0, 1, requestURI, curUrlPMenu);
        try {
            out.print(menuBuilder.toString());
        } catch (IOException e) {
            logger.info("[菜单]获取选中的菜单时发生错误,e.message： " + e.getMessage());
            throw new JspException(e.getMessage());
        }
        return flag ? EVAL_BODY_INCLUDE : SKIP_BODY;
    }

    public StringBuilder getChildMenue(List<Menu> list, int pid, int leavel,
            String requestURI, Menu curUrlPMenu) {
        StringBuilder sb = new StringBuilder();
        Iterator<Menu> iterator = list.iterator();
        while (iterator.hasNext()) {
            Menu subMenu = iterator.next();
            if (subMenu.getMenuType() == MenuType.BUTTON) {// 功能按钮不展示在左侧菜单列
                continue;
            }
            if (pid == subMenu.getpId().intValue()) {
                if (pid == 0) {
                    sb.append("<li class=\"pmenu\">");
                } else {
                    sb.append("<li>");
                }

                StringBuilder sub = getChildMenue(list, subMenu.getId(),
                        leavel + 1, requestURI, curUrlPMenu);
                String i_icon = "open";
                if (!StringUtils.isEmpty(sub.toString()) || pid == 0) {// 判断是否有子菜单
                    String circle_i = "";
                    if (pid != 0) {
                        circle_i = "<i class=\"fa-circle\"></i>";
                    }
                    sb.append("<a class=\"have-sub\" title=\""
                            + subMenu.getName() + "\""
                            + "href=\"javascript:void(0)\">" + circle_i + ""
                            + subMenu.getName() + "<i class=\"" + i_icon
                            + "\"></i></a>");
                    sb.append("<ul class=\"open\">");
                    sb.append(sub);
                    sb.append("</ul>");
                } else {
                    String url = subMenu.getMenuUrl();
                    // url不为空，如果是当前url，那么左侧菜单选中，或者当前请求的url的父菜单选中
                    if (!Strings.isNullOrEmpty(url)
                            && ((requestURI.equals(url)) || url
                                    .equals(curUrlPMenu.getMenuUrl()))) {
                        sb.append("<a class=\"active\" title=\""
                                + subMenu.getName() + "\" href=" + url
                                + "><i class=\"fa-circle\"></i>"
                                + subMenu.getName() + "</a>");
                    } else {
                        if (StringUtils.isEmpty(url)) {
                            url = "/nourl.do";
                        }
                        sb.append("<a href=\"" + url + "\" title=\""
                                + subMenu.getName() + "\""
                                + "><i class=\"fa-circle\"></i>"
                                + subMenu.getName() + "</a>");
                    }

                }
                sb.append("</li>");
            }
        }
        return sb;
    }
}
